<?php
/**
 * @package Bike
 * @subpackage Ajax
 */

/**
 * Class for handling lists storages
 * @author Chrome
 * @package Bike
 * @subpackage Ajax
 */
class Bike_Ajax_ListHandler extends Bike_Ajax_BaseHandler{
	
	/**
	 * Storage for handling
	 * @var Bike_Storage_List
	 */
	protected $storage = null;

	/**
	 * Constructor
	 * @param Bike_Storage_List $storage
	 */
	public function __construct(Bike_Storage_List $storage){
		$this->storage = $storage;
	}
	
	/**
	 * @see Bike_Ajax_BaseHandler::getStorage()
	 * @return Bike_Storage_List
	 */
	public function getStorage(){
		return $this->storage;
	}

	/**
	 * @see Bike_Ajax_IHandler::handle()
	 * @return array
	 */
	public function handle(Bike_IRequest $request){
		$operation = $request->getRequestVar('operation');
		$opResult = false;
		$result = array('success' => false, 'msg' => '');
		switch ($operation){
			case 'update':
				$data = $request->getPostVars();
				if(empty($data['id'])){
					$data['id'] = null;
				}
				try{
					$opResult = $this->storage->updateRecord($data['id'], $data);
					$result = array('success' => $opResult, 'msg' => 'Record updated');
				}catch(Exception $e){
					$result['msg'] = $e->getMessage();
				}
				break;
			case 'insert':
				$data = $request->getPostVars();
				try{
					$opResult = $this->storage->insertRecord($data);
					$result = array('success' => $opResult, 'msg' => 'Record added');
				}catch(Exception $e){
					$result['msg'] = $e->getMessage();
				}
				break;
			case 'delete':
				$data = $request->getPostVars();
				if(!empty($data['id'])){
			   		$opResult = $this->storage->deleteRecord($data['id']);
				}
			   	$result = array('success' => $opResult, 'msg' => 'Record deleted');
				break;
			case null:
				$result = array();
				$offset = (int)$request->getPostVar('start');
				$limit = (int)$request->getPostVar('limit');
				$orderField = $request->getPostVar('sort');
				$orderDirection = $request->getPostVar('dir');
				$order = array();
				if(!empty($orderField) && !empty($orderDirection)){
					$order[$orderField] = $orderDirection;
				}
				$data = $this->storage->getRecordsByConditions(array(), $offset, $limit, $order);
				$result['totalCount'] = $data['totalCount'];
				foreach($data['items'] as $dataItem){
					$dataItem['totalCount'] = $data['totalCount'];
					$result['data'][] = $dataItem;
				}
				break;
		}
		return $result;
	}
}
